package com.android.sharedata.service;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Calendar;

import com.android.sharedata.SynchroService;
import com.android.sharedata.provider.Share;
import com.android.sharedata.provider.ShareDataContract;
import com.android.sharedata.provider.ShareDataContract.Contact;
import com.android.sharedata.provider.ShareDataContract.Files;
import com.android.sharedata.provider.ShareDataContract.Received;
import com.android.sharedata.provider.ShareDataContract.Sent;

import android.app.Service;
import android.content.ContentValues;
import android.content.Intent;
import android.content.SharedPreferences;

import android.database.Cursor;
import android.database.CursorJoiner;
import android.net.Uri;
import android.os.IBinder;

import android.util.Log;

import android.widget.Toast;
import android.widget.TabHost.OnTabChangeListener;

public class BaseManagementService extends Service {
	private Share share;
	private String uriShare;
	private ArrayList<String> listContact = new ArrayList<String>();
	private ArrayList<String> listId = new ArrayList<String>();
	private String Title;
	private String type;
	private String id_File;
	private String id_Share;
	public static final String PREFS_NAME = "MyPrefFile";
	public SharedPreferences myPrefs;

	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		super.onCreate();

	}

	@Override
	public void onStart(Intent intent, int startId) {
		// TODO Auto-generated method stub
		
		//recupere les information pour le partage
		super.onStart(intent, startId);
		uriShare = intent.getStringExtra("imageURI");
		type = intent.getStringExtra("type");
		Title = intent.getStringExtra("title");
		listContact = intent.getStringArrayListExtra("listContact");
		listId = intent.getStringArrayListExtra("listId");

		 addShare(getShare());
		 share.setID_share(Integer.parseInt(id_Share));
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		// TODO Auto-generated method stub
		return super.onStartCommand(intent, flags, startId);

	}

	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
	}
	
	// creer un partage
	public void createShare() {
		myPrefs = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
		Long date = Calendar.getInstance().getTimeInMillis();
		share = new Share(true, myPrefs.getString("login", "null"), Title, type, listContact, uriShare, 3, date);
	}
	
	//recupere un partage
	public Share getShare() {
		createShare();
		return this.share;
	}

	/**
	 * Ajoute un partage a la base (sent et received)
	 * 
	 * @param share
	 */
	private void addShare(Share share) {
		Uri lastId = null;
		ContentValues shr = new ContentValues();

		// insertion dans la table file
		shr.put(Files.TYPE_MIME, share.getType());
		shr.put(Files.URL_SYSTEM, share.getPath_file());
		lastId = getContentResolver().insert(Files.CONTENT_URI, shr);
		id_File = lastId.getLastPathSegment();

		shr.clear();
		// insertion dans la table send
		shr.put(Sent.DATE, share.getDate());
		shr.put(Sent.SYNC_STATUS, share.getSync_status());
		shr.put(Sent.TITLE, share.getName());
		shr.put(Sent.ID_FILE, Integer.parseInt(id_File));
		lastId = getContentResolver().insert(Sent.CONTENT_URI, shr);
		id_Share = lastId.getLastPathSegment();
		
		shr.clear();

		// insertion dans la table Contact
		for (String str : share.getListContact()) {
			shr.put(Contact.ID_CONTACT, str);
			shr.put(Contact.ID_SHARE, id_Share);
			getContentResolver().insert(Contact.CONTENT_URI, shr);
			shr.clear();
		}
	}
	
	//recupere un partage par son id
	private Share getShareById(int id) {
		Share shr = new Share();
		Uri shareUri = Sent.CONTENT_URI;
		Cursor c = getContentResolver().query(
				shareUri,
				new String[] { Sent._ID, Sent.ID_FILE, Sent.TITLE,
						Sent.SYNC_STATUS },
				ShareDataContract.Sent._ID + " = '" + id + "'", null, null);

		if (c.moveToFirst()) {
			String idShare = null;
			String title = null;
			String status = null;
			String idFile = null;
			do {
				idShare = c.getString(c.getColumnIndex(Sent._ID));
				title = c.getString(c.getColumnIndex(Sent.TITLE));
				status = c.getString(c.getColumnIndex(Sent.SYNC_STATUS));
				idFile = c.getString(c.getColumnIndex(Sent.ID_FILE));
				shr.setID_share(Integer.parseInt(idShare));
				shr.setName(title);
				shr.setSync_status(Integer.parseInt(status));
				shr.setID_file(idFile);
			} while (c.moveToNext());
		}
		c.close();

		Uri shareUriFile = Files.CONTENT_URI;
		Cursor c1 = getContentResolver().query(shareUriFile,
				new String[] { Files._ID, Files.TYPE_MIME, Files.URL_SYSTEM },
				null, null, null);

		if (c1.moveToFirst()) {
			String type = null;
			String url = null;
			do {
				type = c1.getString(c1.getColumnIndex(Files.TYPE_MIME));
				url = c1.getString(c1.getColumnIndex(Files.URL_SYSTEM));
				shr.setType(type);
				shr.setPath_file(url);
			} while (c.moveToNext());
		}
		c1.close();

		ArrayList<String> contactList = new ArrayList<String>();
		Uri shareUriContact = Contact.CONTENT_URI;
		Cursor c2 = getContentResolver().query(shareUriContact,
				new String[] { Contact.ID_CONTACT, Contact.ID_SHARE },
				ShareDataContract.Contact.ID_SHARE + " = '" + id + "'", null,
				null);

		if (c2.moveToFirst()) {
			String idcontact = null;
			do {
				idcontact = c2.getString(c2.getColumnIndex(Contact.ID_CONTACT));
				contactList.add(idcontact);
			} while (c2.moveToNext());
		}
		c2.close();
		shr.setListContact(contactList);
		
		return shr;
	}

	/**
	 * recupere tout les partages ayant le status to_sent
	 * 
	 * @return
	 */
	private ArrayList<Share> getSentShare() {
		ArrayList<Share> listShare = new ArrayList<Share>();
		ArrayList<String> listid = new ArrayList<String>();
		Uri shareUri = Sent.CONTENT_URI;
		Cursor c = getContentResolver().query(
				shareUri,
				new String[] { Sent._ID },
				ShareDataContract.Sent.SYNC_STATUS + " = '"
						+ ShareDataContract.Sent.STATUS_TO_SEND + "'", null,
				null);

		if (c.moveToFirst()) {
			String idShare = null;
			do {
				idShare = c.getString(c.getColumnIndex(Sent._ID));
				listid.add(idShare);
			} while (c.moveToNext());
		}

		c.close();
		for (String s : listid) {
			listShare.add(getShareById(Integer.parseInt(s)));
		}

		return listShare;
	}

	/**
	 * Delete un partage dans la base par son id
	 * 
	 * @param id
	 */
	private void deleteSendShareByID(Share share) {
		int id = share.getID_share();
		if (share.isSendShare() == true) {
			ArrayList<String> list = new ArrayList<String>();
			String columns[] = new String[] { Sent._ID, Sent.ID_FILE };
			Uri shareUri = Sent.CONTENT_URI;
			Cursor c = getContentResolver().query(shareUri, columns,
					ShareDataContract.Sent._ID + " = '" + id + "'", null, null);

			if (c.moveToFirst()) {
				String idFile = null;
				do {
					idFile = c.getString(c.getColumnIndex(Sent.ID_FILE));
					list.add(idFile);
				} while (c.moveToNext());
			}
			c.close();
			String strUri = Sent.CONTENT_URI + "/" + id;
			Uri mUri = Uri.parse(strUri);
			getContentResolver().delete(mUri, null, null);

			strUri = Files.CONTENT_URI + "/" + id;
			mUri = Uri.parse(strUri);
			getContentResolver().delete(mUri, null, null);

			list.clear();

			String columns2[] = new String[] { Contact.ID_SHARE,
					Contact.ID_CONTACT };
			shareUri = Contact.CONTENT_URI;

			Cursor c2 = getContentResolver().query(shareUri, columns2,
					ShareDataContract.Contact.ID_SHARE + " = '" + id + "'",
					null, null);

			if (c2.moveToFirst()) {
				String idContact = null;
				do {
					idContact = c2.getString(c2
							.getColumnIndex(Contact.ID_CONTACT));
					list.add(idContact);
				} while (c2.moveToNext());
			}
			c2.close();

			for (String s : list) {
				strUri = Contact.CONTENT_URI + "/" + s;
				mUri = Uri.parse(strUri);
				String where = ShareDataContract.Contact.ID_SHARE + " = '" + id
						+ "'" + "";
				getContentResolver().delete(mUri, where, null);
			}
		} else {
			ArrayList<String> list = new ArrayList<String>();
			String columns[] = new String[] { Received._ID, Received.ID_FILE };
			Uri shareUri = Received.CONTENT_URI;
			Cursor c = getContentResolver().query(shareUri, columns,
					ShareDataContract.Received._ID + " = '" + id + "'", null,
					null);

			if (c.moveToFirst()) {
				String idFile = null;
				do {
					idFile = c.getString(c.getColumnIndex(Received.ID_FILE));
					list.add(idFile);
				} while (c.moveToNext());
			}
			
			c.close();
			String strUri = Received.CONTENT_URI + "/" + id;
			Uri mUri = Uri.parse(strUri);
			getContentResolver().delete(mUri, null, null);

			strUri = Files.CONTENT_URI + "/" + id;
			mUri = Uri.parse(strUri);
			getContentResolver().delete(mUri, null, null);

			list.clear();

			String columns2[] = new String[] { Contact.ID_SHARE,
					Contact.ID_CONTACT };
			shareUri = Contact.CONTENT_URI;

			Cursor c2 = getContentResolver().query(shareUri, columns2,
					ShareDataContract.Contact.ID_SHARE + " = '" + id + "'",
					null, null);

			if (c2.moveToFirst()) {
				String idContact = null;
				do {
					idContact = c2.getString(c2
							.getColumnIndex(Contact.ID_CONTACT));
					list.add(idContact);
				} while (c2.moveToNext());
			}
			c2.close();

			for (String s : list) {
				strUri = Contact.CONTENT_URI + "/" + s;
				mUri = Uri.parse(strUri);
				String where = ShareDataContract.Contact.ID_SHARE + " = '" + id
						+ "'" + "";
				getContentResolver().delete(mUri, where, null);
			}
		}
	}

	/**
	 * delete tout les partages dans la base
	 */
	private void deleteAll() {
		Uri mUri = Sent.CONTENT_URI;
		getContentResolver().delete(mUri, null, null);

		mUri = Received.CONTENT_URI;
		getContentResolver().delete(mUri, null, null);

		mUri = Contact.CONTENT_URI;
		getContentResolver().delete(mUri, null, null);

		mUri = Files.CONTENT_URI;
		getContentResolver().delete(mUri, null, null);
	}

	private void deleteAllSent() {
		Uri mUri = Sent.CONTENT_URI;
		getContentResolver().delete(mUri, null, null);

		mUri = Contact.CONTENT_URI;
		getContentResolver().delete(mUri, null, null);

		mUri = Files.CONTENT_URI;
		getContentResolver().delete(mUri, null, null);
	}

	private void deleteAllReceived() {

		Uri mUri = Received.CONTENT_URI;
		getContentResolver().delete(mUri, null, null);

		mUri = Contact.CONTENT_URI;
		getContentResolver().delete(mUri, null, null);

		mUri = Files.CONTENT_URI;
		getContentResolver().delete(mUri, null, null);
	}

	/**
	 * Update un partage par rapport a son status de syncronisation
	 * 
	 * @param share
	 */
	private void UpdateSendShareByID(Share share) {
		int id = share.getID_share();
		if (share.isSendShare() == true) {
			String str = Sent.CONTENT_URI + "/" + id;
			Uri strUri = Uri.parse(str);
			ContentValues shr = new ContentValues();
			share.setSync_status(1);
			shr.put(Sent.SYNC_STATUS, share.getSync_status());
			String selection = ShareDataContract.Sent.SYNC_STATUS + " = '"
					+ ShareDataContract.Sent.STATUS_TO_SEND + "'";
			getContentResolver().update(strUri, shr, selection, null);
		} else {
			String str = Received.CONTENT_URI + "/" + id;
			Uri strUri = Uri.parse(str);
			ContentValues shr = new ContentValues();
			share.setSync_status(1);
			shr.put(Sent.SYNC_STATUS, share.getSync_status());
			String selection = ShareDataContract.Received.SYNC_STATUS + " = '"
					+ ShareDataContract.Received.STATUS_TO_RECEIVED + "'";
			getContentResolver().update(strUri, shr, selection, null);
		}
	}

	//affichage de la table sent dans la base
	private void displayShareContentProvider() {
		Log.i("BaseManagement", "je suis dans le displayShareContentProvider");
		String columns[] = new String[] { Sent._ID, Sent.TITLE, Sent.DATE,
				Sent.SYNC_STATUS, Sent.ID_FILE };
		Uri shareUri = Sent.CONTENT_URI;
		Cursor cur = getContentResolver().query(shareUri, columns, null, null,
				null);
		Toast.makeText(BaseManagementService.this,
				cur.getCount() + " Share sent", Toast.LENGTH_LONG).show();

		if (cur.moveToFirst()) {
			String name = null;
			do {
				name = cur.getString(cur.getColumnIndex(Sent._ID));
				name = name + "\n titre : "
						+ cur.getString(cur.getColumnIndex(Sent.TITLE));
				name = name + "\n date : "
						+ cur.getString(cur.getColumnIndex(Sent.DATE));
				name = name + "\n sync : "
						+ cur.getString(cur.getColumnIndex(Sent.SYNC_STATUS));
				name = name + "\n id_file : "
						+ cur.getString(cur.getColumnIndex(Sent.ID_FILE));
				Toast.makeText(this, name + " ", Toast.LENGTH_LONG).show();
			} while (cur.moveToNext());
		}
		cur.close();
	}
	
	//affichage de la Contact de la base
	private void displayContactContentProvider() {
		Log.i("BaseManagement", "je suis dans le displayContactContentProvider");
		String columns[] = new String[] { Contact._ID, Contact.ID_CONTACT,
				Contact.ID_SHARE };
		Uri shareUri = Contact.CONTENT_URI;
		Cursor cur = getContentResolver().query(shareUri, columns, null, null,
				null);
		Toast.makeText(BaseManagementService.this, cur.getCount() + " Contact",
				Toast.LENGTH_LONG).show();

		if (cur.moveToFirst()) {
			String name = null;
			do {
				name = cur.getString(cur.getColumnIndex(Contact._ID));
				name = name + "\n id_contact : "
						+ cur.getString(cur.getColumnIndex(Contact.ID_CONTACT));
				name = name + "\n id_share : "
						+ cur.getString(cur.getColumnIndex(Contact.ID_SHARE));
				// Toast.makeText(this, name + " ", Toast.LENGTH_LONG).show();
			} while (cur.moveToNext());
		}
		cur.close();
	}
	
	
	//affichage de la table File de la base
	private void displayFileContentProvider() {
		Log.i("BaseManagement", "je suis dans le displayFileContentProvider");
		String columns[] = new String[] { Files._ID, Files.TYPE_MIME,
				Files.URL_SYSTEM };
		Uri shareUri = Files.CONTENT_URI;
		Cursor cur = getContentResolver().query(shareUri, columns, null, null,
				null);
		Toast.makeText(BaseManagementService.this, cur.getCount() + " File",
				Toast.LENGTH_LONG).show();

		if (cur.moveToFirst()) {
			String name = null;
			do {
				name = cur.getString(cur.getColumnIndex(Files._ID));
				name = name + "\n Type mime : "
						+ cur.getString(cur.getColumnIndex(Files.TYPE_MIME));
				name = name + "\n url system : "
						+ cur.getString(cur.getColumnIndex(Files.URL_SYSTEM));
				// Toast.makeText(this, name + " ", Toast.LENGTH_LONG).show();
			} while (cur.moveToNext());
		}
		cur.close();
	}

	//affichage de la table received de la base
	private void displayShareContentProvider2() {
		Log.i("BaseManagement", "je suis dans le displayShareContentProvider2");
		String columns[] = new String[] { Received._ID, Received.TITLE,
				Received.FROM_LOGIN, Received.ID_RECEIVED, Received.DATE,
				Received.SYNC_STATUS, Received.ID_FILE };
		Uri shareUri = Received.CONTENT_URI;
		Cursor cur = getContentResolver().query(shareUri, columns, null, null,
				null);
		Toast.makeText(BaseManagementService.this,
				cur.getCount() + " Share received", Toast.LENGTH_LONG).show();

		if (cur.moveToFirst()) {
			String name = null;
			do {
				name = cur.getString(cur.getColumnIndex(Received._ID));
				name = name + "\n titre : "
						+ cur.getString(cur.getColumnIndex(Received.TITLE));
				name = name
						+ "\n from_id : "
						+ cur.getString(cur.getColumnIndex(Received.FROM_LOGIN));
				name = name
						+ "\n id_received : "
						+ cur.getString(cur
								.getColumnIndex(Received.ID_RECEIVED));
				name = name + "\n date : "
						+ cur.getString(cur.getColumnIndex(Received.DATE));
				name = name
						+ "\n sync : "
						+ cur.getString(cur
								.getColumnIndex(Received.SYNC_STATUS));
				name = name + "\n id_file : "
						+ cur.getString(cur.getColumnIndex(Received.ID_FILE));
				// Toast.makeText(this, name + " ", Toast.LENGTH_LONG).show();
			} while (cur.moveToNext());
			cur.close();
		}
	}

}
